package com.powernode.config;

/**
 * @version 1.0
 * @Date 2024/8/15 11:38
 * @Author 付~~~
 */

import cn.hutool.core.util.ObjectUtil;
import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign的拦截器，
 *      作用：作用就是解决服务之间的调用没有token的情况
 *
 *   从浏览器 -> A服务 -> B服务
 *   定时器 -> A服务（无token）
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 判断是否有值
        if (ObjectUtil.isNotNull(requestAttributes)){
            // 获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断request是否有值
            if (ObjectUtil.isNotNull(request)){
                // 获取当前请求头中的token值，传递到下一个请求对象的请求头中
                String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
                requestTemplate.header(AuthConstants.AUTHORIZATION,authorization);
                return;
            }
        }
        // 从别的端口到达额某一个服务。没有token
        requestTemplate.header(AuthConstants.AUTHORIZATION,AuthConstants.BEARER + "5ce5157f-4693-43a5-8ca5-44903fd260c5");
    }
}
